import requests
from lxml import etree
import time
# 给定的字符串
# cookie失效，从浏览器中获取
import random

# # 搜素词
# metas = [
#     "electronics",
#     "smartphone"
# ]
def captureali(keywords):
    input_str = 'ali_apache_id=33.63.162.70.1734004273180.161341.5; intl_locale=en_US; acs_usuc_t=acs_rt=34a36082381340e4b5aab07ece4f7f2d&x_csrf=xg7033yohf7h; cna=MbzhH6tfM3ACAXFYXoV9dta1; _gcl_au=1.1.1450212351.1734004275; _m_h5_tk=a7a81d8e21792be604a6d35436e43472_1734006884849; _m_h5_tk_enc=b128b7494d98d2ed44990e03a890f4d0; xlly_s=1; havana_tgc=NTGC_174bb5cc82bc9d8247e2ad2f001c7e08; _hvn_login=13; x_router_us_f=x_alimid=220000791; xman_us_t=x_lid=cn1510000980&sign=y&rmb_pp=86-18923725852&x_user=uTimmNGN5y93sAV+zrpBPSyHC94q9d2XgiellrDHe1I=&ctoken=4lw7dzxqyttt&l_source=aliexpress; sgcookie=E100Ny/IElehQnTmdmqcbmYX29PmGf2QfByUTWkDB9VoMOfb3MBS4eT2TrPfR3h+xjVECCZnOZ2QWLfFCoZeL0YfDu83qqs2WULY4yNpx4JbSx8=; aep_common_f=/pzZQ8kpQtfp8uRJ/RhnvC7vvOCnRbAbOHMBY9wkfuxaEhhNe1VYvQ==; xman_t=f4w/2j/ft4Lc0fOT8B+s4vYQQMEXw9bwm8VeXJdKUXGnex9PO2oYps91kpzSMx79/JdqOcjEWjYtEkh9JijWvKPHoqZmEdIp/Sb5sU679PUBDgU2VCJR8v0lf+bw6yHXvgAwf3p3miODl8jK07I9JwS+NZeHrNq+0kKyA7Cpu75rcf800pSH+v4cAOto7NlPu6a6bUbCq2e+tbBvNeEKz7dfUkuUWTtLvjH7Yovh8Y3NmjRfllIjgY+EpIdmPUHs+95yXknZd76xu4r27JxV6pWr0dbClyq+EprFPso3bJoieXDJS/F8H2StTpR6WruWEyIIqS+srYfxck+TKqoTMWtHwvzb1MYW5QoL5tZUX+gjUa/NFSH3skJ8arsTrPua6Ab3S61ocGYG6ovwSxn8JZHAoEpFDQv622L4vamS+MtVbhnZ3al6tMkUS7Eakh7+CXkM0oOOWhFk180tBQh52ISJ+gPmesYLfo1meqsekf3TOoxgE+6aw1gX/U2Om+XntSj3gDfc8W/eF5f1a10qkZ1egsjyeQuASkziZxELXnF0BVlw2iMrCbYDaIIOTrmmL2uw1Sm5PNDWDBx60e0pRhHjb+whS6nplqpggRH/LrKsgvQqaVLMYuLHTyNwM3Q7Ery/9RHK2c60pIUOzobV60I/lZXcTqLdKfsVheo6AhUEN/WMhpTYcEljZgwl5HBqh8OP3hAYhUGZ0eyB23TInqMCRPsn/zkuNz3Zub7oTw+hCfNP0VT8Ax0sbuZBXcwl; xman_f=AeH4A6mvFWpYcqwudCLGiPYgbry1l0CTmKvYX7XY6kFcm9PpkDzmknH5qsrtlllJfHznNFq7qm49THF6q9W/wCYTDm10LbKn475VnOSMsfrrZ6JYWFM7NPPNKTpk3T3GAsBlJbPNg+H1lCLGfesnQim9+Nz3k9/ckv/jN+05++yyPEIu+BXknCFQOBodeW9FgJazW/PuFpcNbat3jLggze9MWxJQUYg14dbkt4beUGVvxp+5CScTLwM1Kfbfs7JCac8rHClz7xLbknjLcQ8v1+CkHbc8ys6GdJToBcGlJIK2Z8A48Ts+d4+1DC4aJlZcpmajujAK56/H9b6T75S1rXh+oBeeC291zLN1BuWueGrTRIPc3JWKEj5kNoGm0o4b; ali_apache_track=mt=2|ms=|mid=cn1510000980; ali_apache_tracktmp=W_signed=Y; _history_login_user_info={"userName":"fisher","avatar":"","accountNumber":"492524133@qq.com","phonePrefix":"86","hasPwd":true,"expiresTime":1736596291237}; xman_us_f=zero_order=y&x_locale=en_US&x_l=1&x_user=CN|fisher|zhang|cnfm|220000791&x_lid=cn1510000980&x_c_chg=1&acs_rt=34a36082381340e4b5aab07ece4f7f2d; AB_DATA_TRACK=109120_6146.108597_6291; AB_ALG=; AB_STG=st_SE_1729754453849%23stg_3623%2Cst_SE_1730118732538%23stg_3648; lwrid=AgGTurXCokEL0ZlgmdECX39uI2BR; join_status=; aep_usuc_f=isfm=y&site=glo&c_tp=USD&x_alimid=220000791&iss=y&region=CN&b_locale=en_US&ae_u_p_s=2; _gid=GA1.2.1808134043.1734004296; lwrtk=AAEEZ1s+xsA6zyMCe6KxXLIOoE3ZOaJ0O7vFVM3Fdhdh1pI/Q1snFgU=; lwrtk=AAEEZ1s+xsA6zyMCe6KxXLIOoE3ZOaJ0O7vFVM3Fdhdh1pI/Q1snFgU=; _gat=1; __rtbh.uid=%7B%22eventType%22%3A%22uid%22%2C%22id%22%3A%22220000791%22%2C%22expiryDate%22%3A%222025-12-12T11%3A52%3A07.457Z%22%7D; __rtbh.lid=%7B%22eventType%22%3A%22lid%22%2C%22id%22%3A%22zjSOceA6g0veTyeX0lfd%22%2C%22expiryDate%22%3A%222025-12-12T11%3A52%3A07.457Z%22%7D; _ga_VED1YSGNC7=GS1.1.1734004275.1.1.1734004327.8.0.0; _ga=GA1.1.1000352868.1734004275; epssw=7*BEUss6d8UEHhCassT21sussK2ZXOnIeTkgolMJu4ElH0kDEAzrT430IOr6187E3sT2ysusxiUsssssssT21s5G1Rscf6281uwY3-2y_k-suOJTB-ss3qGEBirWeewfaMjdsmnMaxPqm6nUnDFiEf8fZGQPNsZZrwp8C_rZYNwgDid71TOS-Oct0WCDpd3ieKObESu-2suYYxi57wu7co1nAtCoBk-6zuOWfOSW9OKVhrCDZmgx1VugdyfPhMNV8qb9XysIM8LZ5xOReJpmqxOs0-Ekg8asvD3xjh3s6IsOebby13; isg=BP__iAD0pGyTD6BwT87-jbtdjtOJ5FOGCyTvHpHMna71oB8imbfC1kWy5nBe-Cv-; tfstk=g-5qbrqwDSF2RL14jUAZa2Y3IiRvgIqIs1t6SNbMlnxmGjiGUGslltG61dcNSNpGGI_f4cxlJGtffrKM_gIenj16Gf-GvgIXI1t1_PRANtG6codNSMOaAkNQOZQvBCqQA1UzmARMS5tgFKjqD9mYAkNQNh-8KbrCcAQKb889qEcDsh4rqe8MsEvDoz-k7eHimGAgzz8wRfDMmh0kEF8pshjMsz7k2Fc6_Zbiae90JfwY1gmyzK-ho3lFy_8DexQD4flNaTJ2xftrsffyoa_7RihUCHXpcptcq7G2_aYNYeSqquRGzsCeEsq-_Ldk4pCDTVVczI-2K_9x7fjhzNXBU_a39IRDmOOA52rfzsSfk_7sSYA2GTJFgBVKmh65818N6lFPYZXhjOSPLcLuCPCO3cDwnULyAzzPg4EGHgjfkcDtBLApzHaXlAH9nULyAzzrBApkJU-QlE1..; cto_bundle=eLYjWV9mN1J6QjVsYWRPamp2YkpMNCUyRlpVOVBtamVwZVI2dDBadmttTURUMFR6dGNLUXI4SUslMkJHSWhQNDlJc05YSU5NMllVc21nSWE5QkxIYXlURmo4JTJCdm5PSjlrdmVydDhBUmM0RGFJaEp0RDZzVFdTMXprWk1PZTdFMktUMXhtbW5INmFaY2Zod0RxTkklMkZuZm1vbllwaDlkWk10YTFCMmY2d2RaRU1Qa05ZdTNrOCUzRA; intl_common_forever=3MoHBJwWEVO7GyfghmfNi4v52uva7ZHL0JB11KBm/W1txsrkY3yFnQ=='
    # 将字符串分割为键值对
    pairs = input_str.split(';')
    # 创建一个空字典来存储键值对
    result_dict = {}
    # 遍历每个键值对，并将其添加到字典中
    for pair in pairs:
        if '=' in pair:
            key, value = pair.split('=', 1)
            result_dict[key] = value

    # 输出结果字典
    print(result_dict)

    cookies = result_dict

    headers = {
        'accept':
        '*/*',
        'accept-language':
        'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'bx-v':
        '2.5.22',
        'content-type':
        'application/json;charset=UTF-8',
        'origin':
        'https://www.aliexpress.com',
        'priority':
        'u=1, i',
        'referer':
        'https://www.aliexpress.com/w/wholesale-c51.html?page=3&g=y&SearchText=c51',
        'sec-ch-ua':
        '"Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"',
        'sec-ch-ua-mobile':
        '?0',
        'sec-ch-ua-platform':
        '"Windows"',
        'sec-fetch-dest':
        'empty',
        'sec-fetch-mode':
        'cors',
        'sec-fetch-site':
        'same-origin',
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
    }
    # 每一个搜索词抓取的页数
    page = 2
    items = []
    for page_idx in range(page):
        try:
            json_data = {
                'pageVersion': '7ece9c0cc9cf2052db74f0d1b26b7033',
                'target': 'root',
                'data': {
                'page': page_idx + 1,
                'g': 'y',
                'SearchText': keywords,
                'origin': 'y',
            },
            'eventName': 'onChange',
            'dependency': [],
            }
            print('start search ', keywords,  '=》page', page_idx + 1)
            response = requests.post(
                'https://www.aliexpress.com/fn/search-pc/index',
                cookies=cookies,
                headers=headers,
                json=json_data)
            print('response.status_code',response.status_code)
            item_list = response.json().get(
                'data')['result']['mods']['itemList']['content']
            # for idx, item in enumerate(item_list):
            #     product_id = item['productId']
            #     title = item['title']['displayTitle']
            #     # print(json.dumps(item))
            #     print(idx, product_id, title)
            #     print('------------------------')
            print(f'aliexpress->end search sleep->{page_idx}/{page}', keywords)
            items.extend(item_list)

            time.sleep(5 * random.random())
        except Exception as e:
            print(f"抓取aliexpress出错->captureali：{e}")
        finally:
            time.sleep(5 * random.random())

    return items




# if __name__ == '__main__':
#     captureali('c51')
